const app = getApp()

Page({
  data: {
    applications: []
  },

  onLoad() {
    // 检查登录状态
    if (!app.checkLogin()) return
    
    // 获取用户信息
    const userInfo = app.globalData.userInfo
    if (!userInfo || userInfo.role !== 'admin') {
      wx.showToast({
        title: '无权限访问',
        icon: 'none'
      })
      wx.redirectTo({
        url: '/pages/login/login'
      })
      return
    }

    this.loadApplications()
  },

  onShow() {
    // 每次页面显示时重新加载申请列表
    this.loadApplications()
  },

  // 加载申请列表
  async loadApplications() {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'getApplications',
        data: {
          type: 'admin'
        }
      })

      if (result.success) {
        // 格式化时间
        const applications = result.data.map(item => ({
          ...item,
          entryTime: app.formatDateTime(new Date(item.entryTime)),
          expectedLeaveTime: app.formatDateTime(new Date(item.expectedLeaveTime))
        }))

        this.setData({ applications })
      } else {
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('加载申请列表失败', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  // 处理批准申请
  async handleApprove(e) {
    const applicationId = e.currentTarget.dataset.id
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'approveApplication',
        data: {
          applicationId,
          action: 'approve'
        }
      })

      if (result.success) {
        wx.showToast({
          title: '已批准',
          icon: 'success'
        })
        this.loadApplications()
      } else {
        wx.showToast({
          title: result.message || '操作失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('批准申请失败', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },

  // 处理拒绝申请
  async handleReject(e) {
    const applicationId = e.currentTarget.dataset.id
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'approveApplication',
        data: {
          applicationId,
          action: 'reject'
        }
      })

      if (result.success) {
        wx.showToast({
          title: '已拒绝',
          icon: 'success'
        })
        this.loadApplications()
      } else {
        wx.showToast({
          title: result.message || '操作失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('拒绝申请失败', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },

  // 处理退出登录
  handleLogout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          app.clearUserInfo()
          wx.redirectTo({
            url: '/pages/login/login'
          })
        }
      }
    })
  }
}) 